package com.lethelh.jdbc.app.command;

import com.lethelh.jdbc.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class InsertCommand implements Command{
    @Override
    public void execute() {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入商品名称:");
        String name = input.next();
        System.out.println("请输入商品价格:");
        float price = input.nextFloat();
        System.out.println("请输入商品描述:");
        String desc = input.next();

        String sql = "insert into goods (name,price,desp) VALUES (?,?,?)";

        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = DBUtils.getConnection();
            stmt = conn.prepareStatement(sql);
            stmt.setString(1,name);
            stmt.setFloat(2,price);
            stmt.setString(3,desc);

            int res = stmt.executeUpdate();

            if (res == 1){
                System.out.println("新增商品成功!");
                System.out.println("商品名称:"+name+" 商品价格:"+price+" 商品描述:"+desc);
            }else {
                System.out.println("新增商品失败!");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                DBUtils.closeConnection(null,stmt,conn);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
